package com.taiyuan.tongcheng.ui;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import org.json.JSONException;
import org.json.JSONObject;
import org.kymjs.kjframe.KJActivity;
import org.kymjs.kjframe.KJHttp;
import org.kymjs.kjframe.http.HttpCallBack;
import org.kymjs.kjframe.http.HttpConfig;
import org.kymjs.kjframe.http.HttpParams;
import org.kymjs.kjframe.ui.BindView;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.CipherUtils;
import org.kymjs.kjframe.utils.KJLoger;
import org.kymjs.kjframe.utils.StringUtils;
import org.kymjs.kjframe.utils.SystemTool;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import cn.jpush.android.api.JPushInterface;

import com.taiyuan.tongcheng.application.AppConfig;
import com.taiyuan.tongcheng.bean.UserInfo;
import com.taiyuan.tongcheng.db.TcDbHelper;
import com.taiyuan.tongcheng.http.HTTPFieldConstant;
import com.taiyuan.tongcheng.http.TcWebservice;
import com.taiyuan.tongcheng.http.WebData;
import com.taiyuan.tongcheng.jsonparser.TcJsParser;
import com.taiyuan.tongcheng.util.CommonUtil;
import com.taiyuan.tongcheng.util.SharePreferenceUtil;
import com.taiyuan.tongcheng.util.TcUtil;
import com.taiyuan.tongcheng.util.TimeCountUtil;
import com.tytc56.user.R;

/**
 * 
* @Description 注册界面
* @author wzq
* @date 2015-7-23 下午7:13:38
* @update (date)
* @version V1.0
 */
public class RegActivity extends BaseActivity{
	@BindView(id=R.id.etv_reg_phone)
	private EditText phoneEtv ;
	@BindView(id=R.id.etv_reg_phonecode)
	private EditText codeEtv;
	@BindView(id=R.id.etv_reg_tuijian_phone)
	private EditText tuijianPhone;
	@BindView(id=R.id.etv_reg_pwd)
	private EditText pwdEtv;
	@BindView(id=R.id.etv_reg_pwdagin)
	private EditText pwdAginEtv;
	@BindView(id=R.id.img_phone_del,click=true)
	private ImageView phoneDelImg;
	@BindView(id=R.id.btn_regist,click=true)
	private Button  regBtn;
	@BindView(id=R.id.btn_get_phonecode,click=true)
	private Button  getSmsBtn;
	
    // wdiget
    private SharePreferenceUtil spUtil;
    
    @Override
    public void setRootView() {
        setContentView(R.layout.activity_regist);
    }

    @Override
    public void initWidget() {
        super.initWidget();
        initView();
        getSmsBtn.setClickable(false);// 设置不能点击
		// 设置按钮为灰色，这时是不能点击的
	    getSmsBtn.setBackgroundResource(R.drawable.btn_disabled);
        initEtUser();
        spUtil=new SharePreferenceUtil(getApplicationContext(), AppConfig.SHARE_NAME);
        topTv.setText(R.string.regist);
        backBtn.setVisibility(View.GONE);
        rightTv.setVisibility(View.GONE);
    }
    
    @Override
    protected void initView() {
    	super.initView();
    }
    
   /**
    * 
   * @Description: 初始化用户名密码
   * @return void
   * @throws
   * @autour wzq
   * @date 2015-6-29 下午6:57:10
   * @update (date)
    */
    private void initEtUser() {
        if (StringUtils.isEmpty(phoneEtv.getText())) {
            phoneDelImg.setVisibility(View.GONE);
        } else {
        	phoneDelImg.setVisibility(View.VISIBLE);
        }
        
        phoneEtv.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {
            	  if (StringUtils.isEmpty(phoneEtv.getText())) {
            		  phoneDelImg.setVisibility(View.GONE);
                  } else {
                	  phoneDelImg.setVisibility(View.VISIBLE);
                  }
            	  
                  if(!TcUtil.isMobileNO(phoneEtv.getText().toString())){
            		  
            		  getSmsBtn.setClickable(false);// 设置不能点击
            			// 设置按钮为灰色，这时是不能点击的
            		  getSmsBtn.setBackgroundResource(R.drawable.btn_disabled);
            	  }else{
            		  getSmsBtn.setClickable(true);// 设置不能点击
            		  // 设置按钮为灰色，这时是不能点击的
            		  getSmsBtn.setBackgroundResource(R.drawable.selector_btn_blue);
            	  }
            	  
            }
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {}
            @Override
            public void afterTextChanged(Editable s) {}
        });
    }


    @Override
    public void widgetClick(View v) {
        super.widgetClick(v);
        switch (v.getId()) {
		case R.id.btn_regist:
			regist();
			break;
		case R.id.btn_get_phonecode:
			if(SystemTool.checkNet(getApplicationContext())){
				TimeCountUtil  timeCountUtil = new TimeCountUtil(this, 60000, 1000, getSmsBtn);
				timeCountUtil.start();
				getSmsCode();
			}else{
				showCustomToast(getString(R.string.net_work_error));
			}
			break;
		default:
			break;
		}
    }
    
    /**
     * 输入合法性检测
     */
    private boolean inputCheck() {
    	if(StringUtils.isEmpty(phoneEtv.getText())){
    		showErroCustomToast("输入内容不能为空");
            return false;
    	}
    	
    	if(StringUtils.isEmpty(codeEtv.getText())){
     		showErroCustomToast("输入内容不能为空");
    	    return false;
    	}
    	if(StringUtils.isEmpty(pwdEtv.getText())){
     		showErroCustomToast("输入内容不能为空");
    	    return false;
    	}
    	if(StringUtils.isEmpty(pwdAginEtv.getText())){
     		showErroCustomToast("输入内容不能为空");
    	    return false;
    	}
    	if(!SystemTool.checkNet(getApplicationContext())){
     		showErroCustomToast("网络不给力！");
    	    return false;
    	}
    	if(StringUtils.isEmpty(tuijianPhone.getText())){
    		
    	}else{
    		if(!TcUtil.isMobileNO(tuijianPhone.getText().toString())){
    			showErroCustomToast("请输入正确的推荐人电话号码！");
    		   return false;
    		}
    	}
    	
        return true;
    	
    }
    
    /**
     * 
    * @Description: 注册方法
    * @return void
    * @throws
    * @autour wzq
    * @date 2015-7-23 下午7:57:09
    * @update (date)
     */
     private void regist() {
    	 
 		if (!inputCheck()) {
 			return;
 		}
 		TcLoaddingDialog.show();
 		long time= System.currentTimeMillis();
 		HttpConfig config = new HttpConfig();
 		config.cacheTime = 0;
 		KJHttp kjh = new KJHttp(config);
 		HttpParams params = new HttpParams();
 		params.put(HTTPFieldConstant.POST_PARAMS_COMMON_ACT, TcUtil.getApiName(TcWebservice.API.ACCOUNT_REGIST));
 		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_MOBILE, phoneEtv.getText().toString());
 		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_PWD, pwdEtv.getText().toString());
 		params.put("qrPwd",pwdAginEtv.getText().toString());
 		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_SMS, codeEtv.getText().toString());
 		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_FROM, "1");
 		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_DEVID, CommonUtil.getAndroidDeviceUnique(this));
 		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_VER, SystemTool.getAppVersionCode(this));
 		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_REGISTRATIONID, JPushInterface.getRegistrationID(this));
 		if(StringUtils.isEmpty(tuijianPhone.getText().toString())){
 			params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_TUIJIAN, "");
 		}else{
 			params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_TUIJIAN, tuijianPhone.getText().toString());
 		}
 		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_TM, time+"");
 		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_SIGN, 
 				 CipherUtils.md5(phoneEtv.getText().toString()
 							+pwdEtv.getText().toString()
 							+codeEtv.getText().toString()
 							+"1"
 							+CommonUtil.getAndroidDeviceUnique(this)
 							+SystemTool.getAppVersionCode(this)
 							+JPushInterface.getRegistrationID(this)
 							+tuijianPhone.getText().toString()
 							+time
 							+TcWebservice.signSecretKey)
 				);
 		KJLoger.debug(params.getUrlParams().toString());
 		kjh.post(TcWebservice.WEBSERVER_IP+TcWebservice.API.ACCOUNT_REGIST, params,
 				new HttpCallBack() {
 					@Override
 					public void onSuccess(
 							java.util.Map<String, String> headers, byte[] t) {
 						if (t != null) {
							try {
								String str = URLDecoder.decode(new String(t),"UTF-8");
							    WebData webData =TcJsParser.getWedataData(str);
							    KJLoger.debug(str);
							    
							    if (TcLoaddingDialog.isShowing()) {
									TcLoaddingDialog.cancel();
								}
								
							    if(webData.getStatus()==1){
							    	UserInfo info = TcJsParser.getUserInfo(webData
											.getData());
							    	TcDbHelper.saveUser(RegActivity.this, info);
									spUtil.setLoginFlag(1);
									GotoMain();
									showCustomToast(webData.getMsg());
							    }else{
							    	showErroCustomToast(webData.getMsg());
							    }
							    
							
							} catch (UnsupportedEncodingException e) {
								e.printStackTrace();
							}
						
 						}
 					};
 				});
	}
    
     /**
      * 
     * @Description: 获取短信验证码
     * @return void
     * @throws
     * @autour wzq
     * @date 2015-8-24 下午3:42:13
     * @update (date)
      */
     private void getSmsCode() {
    	 
  		long time= System.currentTimeMillis();
  		HttpConfig config = new HttpConfig();
  		config.cacheTime = 0;
  		KJHttp kjh = new KJHttp(config);
  		HttpParams params = new HttpParams();
  		params.put(HTTPFieldConstant.POST_PARAMS_COMMON_ACT, TcUtil.getApiName(TcWebservice.API.ACCOUNT_GET_SMS_REGIST));
  		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_MOBILE, phoneEtv.getText().toString());
  		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_FROM, "1");
  		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_DEVID, CommonUtil.getAndroidDeviceUnique(this));
  		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_VER, SystemTool.getAppVersionCode(this));
  		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_TM, time+"");
  		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_SIGN, 
  				 CipherUtils.md5(phoneEtv.getText().toString()
  							+"1"
  							+CommonUtil.getAndroidDeviceUnique(this)
  							+SystemTool.getAppVersionCode(this)
  							+time
  							+TcWebservice.signSecretKey)
  				);
  		
  		
  		kjh.post(TcWebservice.WEBSERVER_IP+TcWebservice.API.ACCOUNT_GET_SMS_REGIST, params,
  				new HttpCallBack() {
  					@Override
  					public void onSuccess(
  							java.util.Map<String, String> headers, byte[] t) {
  						if (t != null) {
  							try {
								String str = URLDecoder.decode(new String(t),"UTF-8");
							    WebData webData =TcJsParser.getWedataData(str);
							    if(webData.getStatus()==1){
							    	ViewInject.toast(webData.getMsg());
							    	
							    }else{
							    	ViewInject.toast(webData.getMsg());
							    }
							
							} catch (UnsupportedEncodingException e) {
								e.printStackTrace();
							}
  						}
  					};
  				});
	}
    
    
}
